package cn.iocoder.yudao.module.system.controller.admin.erp.warehousein;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.erp.sku.vo.SkuItem;
import cn.iocoder.yudao.module.system.controller.admin.erp.warehousein.vo.WarehouseInPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.erp.warehousein.vo.WarehouseInRespVO;
import cn.iocoder.yudao.module.system.controller.admin.erp.warehousein.vo.WarehouseInSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.erp.warehouseinsku.vo.WarehouseInRespExcelImportVO;
import cn.iocoder.yudao.module.system.controller.admin.erp.warehouseinsku.vo.WarehouseInSkuSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.erp.warehouseinventorysku.vo.WarehouseInventorySkuSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.sku.SkuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.warehouse.WarehouseDO;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.warehousein.WarehouseInDO;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.warehouseinsku.WarehouseInSkuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.warehouseinventory.WarehouseInventoryDO;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.warehouseinventorysku.WarehouseInventorySkuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.warehouseoutsuk.WarehouseOutSukDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.framework.CommonConstant;
import cn.iocoder.yudao.module.system.service.erp.customermanage.CustomerManageService;
import cn.iocoder.yudao.module.system.service.erp.operatelog.ErpOperateLogService;
import cn.iocoder.yudao.module.system.service.erp.sku.SkuService;
import cn.iocoder.yudao.module.system.service.erp.warehouse.WarehouseService;
import cn.iocoder.yudao.module.system.service.erp.warehousein.WarehouseInService;
import cn.iocoder.yudao.module.system.service.erp.warehouseinsku.WarehouseInSkuService;
import cn.iocoder.yudao.module.system.service.erp.warehouseinventory.WarehouseInventoryService;
import cn.iocoder.yudao.module.system.service.erp.warehouseinventorysku.WarehouseInventorySkuService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.*;
import jakarta.servlet.http.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exceptionErr;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import org.springframework.web.multipart.MultipartFile;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static java.util.Arrays.asList;

@Tag(name = "管理后台 - 入库单")
@RestController
@RequestMapping("/erp/warehouse-in")
@Validated
public class WarehouseInController {

    @Resource
    private WarehouseInService warehouseInService;
    @Resource
    private WarehouseInSkuService warehouseInSkuService;
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private AdminUserService userService;
    @Resource
    private SkuService skuService;
    @Resource
    private WarehouseInventoryService warehouseInventoryService;
    @Resource
    private WarehouseInventorySkuService warehouseInventorySkuService;
    @Resource
    private CustomerManageService customerManageService;
    @Resource
    private ErpOperateLogService erpOperateLogService;
    @PostMapping("/create")
    @Operation(summary = "创建入库单")
    @PreAuthorize("@ss.hasPermission('erp:warehouse-in:create')")
    public CommonResult<Long> createWarehouseIn(@Valid @RequestBody WarehouseInSaveReqVO createReqVO) {
        List<SkuItem> skuItems = createReqVO.getSkuItems();
        createReqVO.setOperateBy(SecurityFrameworkUtils.getLoginUserId());
        Map<String, BigDecimal> NEW_SKU_NUM =skuItems.stream().collect(Collectors.toMap(SkuItem::getSku, SkuItem::getNum));
        List<String>skuVals=NEW_SKU_NUM.keySet().stream().toList();
        if(skuVals.isEmpty()){
            throw exceptionErr(500,"sku未选择");
        }
        List<SkuDO>skus=new ArrayList<>();
        for(String skuVal:skuVals){
            SkuDO sku = skuService.getSku(skuVal);
            if (ObjectUtil.isNull(sku)) {
                throw exceptionErr(500, "skuId不存在");
            }
            if (NEW_SKU_NUM.get(skuVal).compareTo(BigDecimal.ZERO)>0){
                throw exceptionErr(500,sku.getSku()+"sku数量不能为0");
            }
            skus.add(sku);
        }

        Long warehouseId = createReqVO.getWarehouseId();
        if(ObjectUtil.isNull(warehouseId)){
            throw exceptionErr(500,"仓库id不能为空");
        }
        WarehouseDO warehouse = warehouseService.getWarehouse(warehouseId);
        if(ObjectUtil.isNull(warehouse)){
            throw exceptionErr(500,"仓库id不存在");
        }
        Long customerId = createReqVO.getCustomerId();
        if(ObjectUtil.isNull(customerId)){
            throw exceptionErr(500,"客户id不能为空");
        }
        AdminUserDO customer = userService.getUser(customerId);
        if(ObjectUtil.isNull(customer)){
            throw exceptionErr(500,"客户id不存在");
        }
        Long inWarehouseId = warehouseInService.createWarehouseIn(createReqVO);
        skus.forEach(s->{
            WarehouseInSkuSaveReqVO warehouseInSkuSaveReqVO=new WarehouseInSkuSaveReqVO();
            warehouseInSkuSaveReqVO.setInWarehouseId(inWarehouseId);//入库单
            warehouseInSkuSaveReqVO.setSku(s.getSku());
            warehouseInSkuSaveReqVO.setLength(s.getLength());
            warehouseInSkuSaveReqVO.setWeight(s.getWeight());
            warehouseInSkuSaveReqVO.setWidth(s.getWidth());
            warehouseInSkuSaveReqVO.setHeight(s.getHeight());
            warehouseInSkuSaveReqVO.setNum(NEW_SKU_NUM.get(s.getSku()));
            warehouseInSkuService.createWarehouseInSku(warehouseInSkuSaveReqVO);
        });
        WarehouseInventoryDO warehouseInventory = warehouseInventoryService.getOrCrateWarehouseInventory( warehouseId,customerId);
        List<WarehouseInventorySkuDO> warehouseInventorySkuList = warehouseInventorySkuService.getWarehouseInventorySkuList(warehouseId,customerId);
        Map<String, WarehouseInventorySkuDO>OLD_SKU_ITEM=warehouseInventorySkuList.stream().collect(Collectors.toMap(WarehouseInventorySkuDO::getSku, e -> e));
//        Long inventoryId = warehouseInventory.getId();
        if(OLD_SKU_ITEM.isEmpty()){
            skus.forEach(e->{
                WarehouseInventorySkuSaveReqVO newItem=new WarehouseInventorySkuSaveReqVO();
                newItem.setHeight(e.getHeight());
                newItem.setWeight(e.getWeight());
                newItem.setWidth(e.getWidth());
                newItem.setLength(e.getLength());
                newItem.setNum(NEW_SKU_NUM.get(e.getSku()));
                newItem.setCustomerId(customerId);
                newItem.setWarehouseId(warehouseId);
//                newItem.setInventoryId(inventoryId);
                newItem.setSku(e.getSku());
                warehouseInventorySkuService.createWarehouseInventorySku(newItem);
            });
        }else{
            skus.forEach(e->{
                WarehouseInventorySkuDO oldItem=OLD_SKU_ITEM.get(e.getSku());
                if(ObjectUtil.isNull(oldItem)){
                    WarehouseInventorySkuSaveReqVO newItem=new WarehouseInventorySkuSaveReqVO();
                    newItem.setHeight(e.getHeight());
                    newItem.setWeight(e.getWeight());
                    newItem.setWidth(e.getWidth());
                    newItem.setLength(e.getLength());
                    newItem.setNum(NEW_SKU_NUM.get(e.getSku()));
                    newItem.setCustomerId(customerId);
                    newItem.setWarehouseId(warehouseId);
//                   newItem.setInventoryId(inventoryId);
                    newItem.setSku(e.getSku());
                    warehouseInventorySkuService.createWarehouseInventorySku(newItem);
                }else {
                    // 更新
                    WarehouseInventorySkuSaveReqVO updateObj = BeanUtils.toBean(oldItem, WarehouseInventorySkuSaveReqVO.class);
                    oldItem.setHeight(e.getHeight());
                    oldItem.setWeight(e.getWeight());
                    oldItem.setWidth(e.getWidth());
                    oldItem.setLength(e.getLength());
                    oldItem.setNum(oldItem.getNum().add(NEW_SKU_NUM.get(e.getSku())));
                    oldItem.setCustomerId(customerId);
                    oldItem.setWarehouseId(warehouseId);
//                newItem.setInventoryId(inventoryId);
                    oldItem.setSku(e.getSku());
                    warehouseInventorySkuService.updateWarehouseInventorySku(updateObj);
                }
            });
        }
        return success(inWarehouseId);
    }

    @PutMapping("/update")
    @Operation(summary = "更新入库单")
    @PreAuthorize("@ss.hasPermission('erp:warehouse-in:update')")
    public CommonResult<Boolean> updateWarehouseIn(@Valid @RequestBody WarehouseInSaveReqVO updateReqVO) {
        Long inWarehouseId = updateReqVO.getId();
        WarehouseInDO warehouseIn = warehouseInService.getWarehouseIn(inWarehouseId);
        List<SkuItem> skuItems = updateReqVO.getSkuItems();
        Map<String, BigDecimal> NEW_SKU_NUM =skuItems.stream().collect(Collectors.toMap(SkuItem::getSku, SkuItem::getNum));
        List<String>skuVals=NEW_SKU_NUM.keySet().stream().toList();
        if(skuVals.isEmpty()){
            throw exceptionErr(500,"sku未选择");
        }
        for(String skuVal:skuVals){
            SkuDO sku = skuService.getSku(skuVal);
            if (ObjectUtil.isNull(sku)){
                throw exceptionErr(500,"skuId不存在");
            }
            if (NEW_SKU_NUM.get(sku).compareTo(BigDecimal.ZERO)>0){
                throw exceptionErr(500,sku.getSku()+"sku数量不能为0");
            }
        }
        Long newWarehouseId = updateReqVO.getWarehouseId();
        if(ObjectUtil.isNull(newWarehouseId)){
            throw exceptionErr(500,"仓库id不能为空");
        }
        WarehouseDO warehouse = warehouseService.getWarehouse(newWarehouseId);
        if(ObjectUtil.isNull(warehouse)){
            throw exceptionErr(500,"仓库id不存在");
        }
        Long newCustomerId = updateReqVO.getCustomerId();
        if(ObjectUtil.isNull(newCustomerId)){
            throw exceptionErr(500,"客户id不能为空");
        }
        AdminUserDO customer = userService.getUser(newCustomerId);
        if(ObjectUtil.isNull(customer)){
            throw exceptionErr(500,"客户id不存在");
        }
        warehouseInService.updateWarehouseIn(updateReqVO);




//        Long oldWarehouseId=warehouseIn.getWarehouseId();//旧仓库id
//        Long oldCustomerId=warehouseIn.getCustomerId();//旧客户id
//        Boolean replaceWarehouse=!ObjectUtil.equal(oldWarehouseId,newWarehouseId);
//        Boolean replaceCustomer=!ObjectUtil.equal(oldCustomerId,oldCustomerId);
//
//
//        List<WarehouseInSkuDO>oldInSkus=warehouseInSkuService.findInWarehouseIdWarehouseInSku(inWarehouseId);
//
//         Map<String,WarehouseInSkuDO>OLD_SKU_ITEM=oldInSkus.stream().collect(Collectors.toMap(WarehouseInSkuDO::getSku,e->e));
//         //原来要更新的
//        List<Map.Entry<String,WarehouseInSkuDO>>oldUpdates=OLD_SKU_ITEM.entrySet().stream().filter(e -> NEW_SKU_NUM.containsKey(e.getKey())).toList();
//        //原来要删的
//        List<Map.Entry<String,WarehouseInSkuDO>>oldDels=OLD_SKU_ITEM.entrySet().stream().filter(e -> !NEW_SKU_NUM.containsKey(e.getKey())).toList();
//        List<WarehouseInventorySkuDO> oldWarehouseInventorySkuList = warehouseInventorySkuService.getWarehouseInventorySkuList(oldWarehouseId,oldCustomerId);
//
//        List<WarehouseInventorySkuDO> newWarehouseInventorySkuList = warehouseInventorySkuService.getWarehouseInventorySkuList(newWarehouseId,newCustomerId);
//        Map<String, WarehouseInventorySkuDO>OLD_I_SKU_ITEM=oldWarehouseInventorySkuList.stream().collect(Collectors.toMap(WarehouseInventorySkuDO::getSku, e -> e));
//        Map<String, WarehouseInventorySkuDO>NEW_I_SKU_ITEM=newWarehouseInventorySkuList.stream().collect(Collectors.toMap(WarehouseInventorySkuDO::getSku, e -> e));
//        List<WarehouseInSkuDO>oldUpdateItems=new ArrayList<>();
//        List<WarehouseInSkuDO>oldDelItems=new ArrayList<>();
//        /**
//         * 入库
//         * 库存 = 2
//         *   3-2=1  2-1=1
//         *   3-3=0   2-(0)=2
//         *   3-5=-2 2-(-2)=4
//         */
//        if(oldUpdates.isEmpty()){  //原来要更新的
//            for (Map.Entry<String, WarehouseInSkuDO>e:oldUpdates) {
//                WarehouseInSkuDO oldSku=e.getValue();
//                String key = e.getKey();
//                WarehouseInventorySkuDO iSku=OLD_I_SKU_ITEM.get(key);
//                BigDecimal iNum = iSku.getNum();
//                BigDecimal nnNum = NEW_SKU_NUM.get(key);
//                BigDecimal onNum = oldSku.getNum();
//                BigDecimal zNum = iNum.subtract(onNum.subtract(nnNum));//库存变化结果
//                if (zNum.compareTo(BigDecimal.ZERO) < 0) { // 检查是否小于等于0
//                    throw exceptionErr(500, key + " sku数量修改为:"+iNum+" 会影响库存数据");
//                }
//                SkuDO sku = skuService.getSku(e.getKey());
//                oldSku.setLength(sku.getLength());
//                oldSku.setWeight(sku.getWeight());
//                oldSku.setWidth(sku.getWidth());
//                oldSku.setHeight(sku.getHeight());
//                oldSku.setNum(nnNum);
//                WarehouseInSkuSaveReqVO oldSkuObj = BeanUtils.toBean(oldSku, WarehouseInSkuSaveReqVO.class);
//                warehouseInSkuService.updateWarehouseInSku(oldSkuObj);
//                WarehouseInventorySkuSaveReqVO newItem=new WarehouseInventorySkuSaveReqVO();
//                newItem.setHeight(sku.getHeight());
//                newItem.setWeight(sku.getWeight());
//                newItem.setWidth(sku.getWidth());
//                newItem.setLength(sku.getLength());
//                newItem.setNum(NEW_SKU_NUM.get(sku.getSku()));
//                newItem.setCustomerId(newCustomerId);
//                newItem.setWarehouseId(newWarehouseId);
////                newItem.setInventoryId(inventoryId);
//                newItem.setSku(e.getKey());
//                warehouseInventorySkuService.createWarehouseInventorySku(newItem);
//
////                WarehouseInSkuSaveReqVO warehouseInSkuSaveReqVO=new WarehouseInSkuSaveReqVO();
////                warehouseInSkuSaveReqVO.setInWarehouseId(inWarehouseId);//入库单
////                warehouseInSkuSaveReqVO.setSku(sku.getSku());
////                warehouseInSkuSaveReqVO.setLength(sku.getLength());
////                warehouseInSkuSaveReqVO.setWeight(sku.getWeight());
////                warehouseInSkuSaveReqVO.setWidth(sku.getWidth());
////                warehouseInSkuSaveReqVO.setHeight(sku.getHeight());
////                warehouseInSkuSaveReqVO.setNum(NEW_SKU_NUM.get(sku.getSku()));
////                warehouseInSkuService.createWarehouseInSku(warehouseInSkuSaveReqVO);
////                WarehouseInventorySkuSaveReqVO newItem=new WarehouseInventorySkuSaveReqVO();
////                newItem.setHeight(sku.getHeight());
////                newItem.setWeight(sku.getWeight());
////                newItem.setWidth(sku.getWidth());
////                newItem.setLength(sku.getLength());
////                newItem.setNum(NEW_SKU_NUM.get(sku.getSku()));
////                newItem.setCustomerId(newCustomerId);
////                newItem.setWarehouseId(newWarehouseId);
//////                newItem.setInventoryId(inventoryId);
////                newItem.setSku(e.getKey());
////                warehouseInventorySkuService.createWarehouseInventorySku(newItem);
//            }
//        }
//        /**
//         * 入库
//         * 库存 = 2
//         *   3-2=1  2-1=1
//         *   3-3=0   2-(0)=2
//         *   3-5=-2 2-(-2)=4
//         */
//        if(oldDels.isEmpty()){ //原来要删的
//            for (Map.Entry<String, WarehouseInSkuDO> e : oldDels) {
//
//
////                WarehouseInSkuSaveReqVO warehouseInSkuSaveReqVO=new WarehouseInSkuSaveReqVO();
////                warehouseInSkuSaveReqVO.setInWarehouseId(inWarehouseId);//入库单
////                warehouseInSkuSaveReqVO.setSku(sku.getSku());
////                warehouseInSkuSaveReqVO.setLength(sku.getLength());
////                warehouseInSkuSaveReqVO.setWeight(sku.getWeight());
////                warehouseInSkuSaveReqVO.setWidth(sku.getWidth());
////                warehouseInSkuSaveReqVO.setHeight(sku.getHeight());
////                warehouseInSkuSaveReqVO.setNum(NEW_SKU_NUM.get(sku.getSku()));
////                warehouseInSkuService.createWarehouseInSku(warehouseInSkuSaveReqVO);
////                WarehouseInventorySkuSaveReqVO newItem=new WarehouseInventorySkuSaveReqVO();
////                newItem.setHeight(sku.getHeight());
////                newItem.setWeight(sku.getWeight());
////                newItem.setWidth(sku.getWidth());
////                newItem.setLength(sku.getLength());
////                newItem.setNum(NEW_SKU_NUM.get(sku.getSku()));
////                newItem.setCustomerId(newCustomerId);
////                newItem.setWarehouseId(newWarehouseId);
//////                newItem.setInventoryId(inventoryId);
////                newItem.setSku(e.getKey());
////                warehouseInventorySkuService.createWarehouseInventorySku(newItem);
//            }
//        }
//
//
//
//        //新增之前没有
//        NEW_SKU_NUM.entrySet().stream().filter(e->!OLD_SKU_ITEM.containsKey(e.getKey())).forEach(e->{
//            SkuDO sku = skuService.getSku(e.getKey());
//            WarehouseInSkuSaveReqVO warehouseInSkuSaveReqVO=new WarehouseInSkuSaveReqVO();
//            warehouseInSkuSaveReqVO.setInWarehouseId(inWarehouseId);//入库单
//            warehouseInSkuSaveReqVO.setSku(sku.getSku());
//            warehouseInSkuSaveReqVO.setLength(sku.getLength());
//            warehouseInSkuSaveReqVO.setWeight(sku.getWeight());
//            warehouseInSkuSaveReqVO.setWidth(sku.getWidth());
//            warehouseInSkuSaveReqVO.setHeight(sku.getHeight());
//            warehouseInSkuSaveReqVO.setNum(NEW_SKU_NUM.get(sku.getSku()));
//            warehouseInSkuService.createWarehouseInSku(warehouseInSkuSaveReqVO);
//            WarehouseInventorySkuSaveReqVO newItem=new WarehouseInventorySkuSaveReqVO();
//            newItem.setHeight(sku.getHeight());
//            newItem.setWeight(sku.getWeight());
//            newItem.setWidth(sku.getWidth());
//            newItem.setLength(sku.getLength());
//            newItem.setNum(NEW_SKU_NUM.get(sku.getSku()));
//            newItem.setCustomerId(newCustomerId);
//            newItem.setWarehouseId(newWarehouseId);
////                newItem.setInventoryId(inventoryId);
//            newItem.setSku(e.getKey());
//            warehouseInventorySkuService.createWarehouseInventorySku(newItem);
//        });
////        skus.forEach(s->{
////
////            WarehouseInSkuSaveReqVO warehouseInSkuSaveReqVO=new WarehouseInSkuSaveReqVO();
////            warehouseInSkuSaveReqVO.setInWarehouseId(inWarehouseId);//入库单
////            warehouseInSkuSaveReqVO.setSku(s.getSku());
////            warehouseInSkuSaveReqVO.setLength(s.getLength());
////            warehouseInSkuSaveReqVO.setWeight(s.getWeight());
////            warehouseInSkuSaveReqVO.setWidth(s.getWidth());
////            warehouseInSkuSaveReqVO.setHeight(s.getHeight());
////            warehouseInSkuSaveReqVO.setNum(SKUID_NUM.get(s.getId()));
////            warehouseInSkuService.createWarehouseInSku(warehouseInSkuSaveReqVO);
////
////        });
//



        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除入库单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:warehouse-in:delete')")
    public CommonResult<Boolean> deleteWarehouseIn(@RequestParam("id") Long id) {
       WarehouseInDO warehouseIn = warehouseInService.getWarehouseIn(id);
        warehouseInService.deleteWarehouseIn(id);
        List<WarehouseInSkuDO>oldInSkus=warehouseInSkuService.findInWarehouseIdWarehouseInSku(id);
        for(WarehouseInSkuDO inSkuDO:oldInSkus){
            warehouseInSkuService.deleteWarehouseInSku(inSkuDO.getId());
        }
        Long customerId = warehouseIn.getCustomerId();
        Long warehouseId = warehouseIn.getWarehouseId();
        Map<String,BigDecimal>SKU_NUM=oldInSkus.stream().collect(Collectors.toMap(WarehouseInSkuDO::getSku, WarehouseInSkuDO::getNum));
        List<WarehouseInventorySkuDO> wiSkuList = warehouseInventorySkuService.getWarehouseInventorySkuList(warehouseId,customerId);
        for(WarehouseInventorySkuDO wiskuItem:wiSkuList){
            String sku = wiskuItem.getSku();
            BigDecimal iNum = wiskuItem.getNum();//库存
            BigDecimal oNum = SKU_NUM.get(sku);//入库单
            if(iNum.compareTo(oNum)<0){
                  throw exceptionErr(500,sku+"库存不足无法删除");
             }
        }
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得入库单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:warehouse-in:query')")
    public CommonResult<WarehouseInRespVO> getWarehouseIn(@RequestParam("id") Long id) {
        WarehouseInRespVO warehouseIn = BeanUtils.toBean(warehouseInService.getWarehouseIn(id), WarehouseInRespVO.class);
        warehouseIn.setWarehouse(warehouseService.getWarehouse(warehouseIn.getWarehouseId()).getName());
        warehouseIn.setCustomer(userService.getUser(warehouseIn.getCustomerId()).getNickname());
        List<WarehouseInSkuDO> skuList = warehouseInSkuService.findInWarehouseIdWarehouseInSku(warehouseIn.getId());
        warehouseIn.setSkus(skuList);
        return success(warehouseIn);
    }

    @GetMapping("/page")
    @Operation(summary = "获得入库单分页")
    @PreAuthorize("@ss.hasPermission('erp:warehouse-in:query')")
        public CommonResult<PageResult<WarehouseInRespVO>> getWarehouseInPage(@Valid WarehouseInPageReqVO pageReqVO) {
        Long loginUserId= SecurityFrameworkUtils.getLoginUserId();
        AdminUserDO user=userService.getUser(loginUserId);
        String roleCode=user.getRoleCode();

        if(ObjectUtil.equal(loginUserId,1L)||asList(CommonConstant.ERP_ADMIN,CommonConstant.ERP_SUPER_ADMIN).contains(roleCode)){
        List<Long>customerIds=new ArrayList<>();
        if(ObjectUtil.contains(CommonConstant.ERP_ADMIN,roleCode)){customerIds=customerManageService.getCustomerIds(loginUserId);}
        pageReqVO.setCustomerIds(customerIds);
        }

        PageResult<WarehouseInRespVO> pageResult=BeanUtils.toBean(warehouseInService.getWarehouseInPage(pageReqVO), WarehouseInRespVO.class);
        pageResult.getList().forEach(e->{
        Long customerId = e.getCustomerId();
        Long warehouseId = e.getWarehouseId();
        e.setWarehouse(warehouseService.getWarehouse(warehouseId).getName());
        e.setCustomer(userService.getUser(customerId).getNickname());
        List<WarehouseInSkuDO> skuList = warehouseInSkuService.findInWarehouseIdWarehouseInSku(e.getId());
        e.setSkus(skuList);});
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出入库单 Excel")
    @PreAuthorize("@ss.hasPermission('erp:warehouse-in:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportWarehouseInExcel(@Valid WarehouseInPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<WarehouseInDO> list = warehouseInService.getWarehouseInPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "入库单.xls", "数据", WarehouseInRespVO.class,
                        BeanUtils.toBean(list, WarehouseInRespVO.class));
    }

    @PostMapping("/import-excel")
    @Operation(summary = "导入入库单 Excel")
    @PreAuthorize("@ss.hasPermission('erp:warehouse-in:import')")
    @ApiAccessLog(operateType = EXPORT)
    public void importWarehouseInExcel(@RequestParam("file") MultipartFile file,
                                       @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<WarehouseInRespExcelImportVO>list=ExcelUtils.read(file, WarehouseInRespExcelImportVO.class);
        long count = list.stream().filter(e -> {
            String customer = e.getCustomer();
            String warehouse = e.getWarehouse();
            BigDecimal num = e.getNum();
            LocalDateTime inWarehouseTime = e.getInWarehouseTime();
            String sku = e.getSku();
            return StrUtil.isBlank(customer) || StrUtil.isBlank(warehouse) || ObjectUtil.isNull(num) || ObjectUtil.isNull(inWarehouseTime) || StrUtil.isBlank(sku) ;
        }).count();
        if(count>0){
            throw exceptionErr(500,"请检查文件");
        }
        Map<String, List<WarehouseInRespExcelImportVO>> cw_wor = list.stream().collect(Collectors.groupingBy(e -> e.getCustomer()+"-" + e.getWarehouse()));
        List<WarehouseInSaveReqVO> wList=new ArrayList<>();
        for(Map.Entry<String,List<WarehouseInRespExcelImportVO>> e:cw_wor.entrySet()){
            String[] c_w = e.getKey().split("-");
            List<WarehouseInRespExcelImportVO> value = e.getValue();
            String c = c_w[0];
            String w = c_w[1];
            AdminUserDO customer = userService.getUserByUsername(c,CommonConstant.ERP_CUSTOMER);
            if(ObjectUtil.isNull(customer)){
                throw exceptionErr(500,"客户名称不存在");
            }
            WarehouseDO warehouseDO = warehouseService.byNameGetWarehouse(w);
            if(ObjectUtil.isNull(warehouseDO)){
                throw exceptionErr(500,"仓库名称不存在");
            }
            WarehouseInSaveReqVO reqVO = new WarehouseInSaveReqVO();
            reqVO.setWarehouseId(warehouseDO.getId());
            reqVO.setCustomerId(customer.getId());
            reqVO.setOperateBy(SecurityFrameworkUtils.getLoginUserId());
            reqVO.setInWarehouseTime(value.get(0).getInWarehouseTime());
            List<SkuItem> skuItems=value.stream().map(v -> {
                SkuItem skuItem = new SkuItem();
                skuItem.setNum(v.getNum());
                skuItem.setSku(v.getSku());
                return skuItem;
            }).toList();
            reqVO.setSkuItems(skuItems);
            wList.add(reqVO);
        }
        wList.forEach(this::createWarehouseIn);
//        cw_wor.entrySet().stream().map(e->{
//            String[] c_w = e.getKey().split("-");
//            String c = c_w[0];
//            String w = c_w[1];
//            AdminUserDO customer = userService.getUserByUsername(c, CommonConstant.ERP_CUSTOMER);
//            WarehouseDO warehouseDO = warehouseService.byNameGetWarehouse(w);
//            WarehouseInSaveReqVO reqVO = new WarehouseInSaveReqVO();
//            reqVO.setWarehouseId(warehouseDO.getId());
//            return
//        }).collect(Collectors.toList());


//        WarehouseInSaveReqVO


    }

}